package fire.and.near.challenger;

import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;

import com.facebook.Response;

import fire.and.near.challenger.database.ChallengeModel;
import fire.and.near.challenger.database.DatabaseActivity;
import fire.and.near.challenger.database.DatabaseAsyncTask;
import fire.and.near.challenger.database.DatabaseAsyncTask.DatabaseQueryOptions;
import fire.and.near.challenger.database.DatabaseResponse;
import fire.and.near.challenger.database.TableConstants.ChallengesTable;
import fire.and.near.challenger.database.TableConstants.FriendsTable;
import fire.and.near.challenger.facebook.FacebookActionAdapter;
import fire.and.near.challenger.facebook.MessageBuilder;
import fire.and.near.challenger.facebook.MessageType;
import fire.and.near.challenger.util.ChallengeUtil;
import fire.and.near.challenger.util.Consts;
import fire.and.near.challenger.web.HttpRequestSender;
import fire.and.near.challenger.web.ServerResponse;
import fire.and.near.challenger.web.WebActivity;

public class PendingChallengesActivity extends ActionBarActivity implements
		DatabaseActivity, WebActivity {

	private boolean databaseWorking = false;
	private long fbID;
	private ListView listViewPending = null;
	private PendingChallengesListAdapter adapter = null;
	private List<ChallengeModel> pendingChallenges = null;
	private ChallengeModel selectedChallenge = null;
	private boolean deleteAll = false; // ignores spamming the buttons
	private boolean uploadAll = false;
	private static int DETAILS_REQUEST_CODE = 9007; // why not?
	
	private boolean fbFlag = false; // magic
	private boolean dbFlag = false; // magic x2
	private boolean toMain = false;
	private int chCount = 0;
	private int mSize = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_pending_challenges);

		Log.i("click", "gg");

		if (HttpRequestSender.isNetworkAvailable(this)) {
			this.fbID = LoginActivity.mFbHelper.getMyFacebookId();
			this.listViewPending = (ListView) findViewById(R.id.listView_challenges);
			final Activity context = this;
			this.listViewPending
					.setOnItemClickListener(new OnItemClickListener() {

						@Override
						public void onItemClick(AdapterView<?> parent,
								View view, int position, long id) {

							Log.i("click", "ff");

							selectedChallenge = pendingChallenges.get(position);
							
							Intent i = new Intent(context,
									PendingChallengeDetailsActivity.class);
							Bundle extras = new Bundle();

							extras.putInt(ChallengesTable.ID, pendingChallenges
									.get(position).getID());
							extras.putString(ChallengesTable.DESCRIPTION,
									pendingChallenges.get(position)
											.getDescription());
							extras.putString(ChallengesTable.ANSWER,
									pendingChallenges.get(position).getAnswer());
							extras.putString(ChallengesTable.HASHTAG,
									pendingChallenges.get(position)
											.getHashtag());
							extras.putString(ChallengesTable.PHOTO_PATH,
									pendingChallenges.get(position)
											.getPhotoPath());
							extras.putInt(ChallengesTable.CHALLENGE_TYPE,
									pendingChallenges.get(position)
											.getChallengeType().asInt());
							extras.putLong(ChallengesTable.CHALLENGER_ID,
									pendingChallenges.get(position)
											.getChallenger().getFbID());
							extras.putString(FriendsTable.NAME,
									pendingChallenges.get(position)
											.getChallenger().getName());
							extras.putBoolean(ChallengesTable.ACCEPTED,
									pendingChallenges.get(position)
											.isAccepted());
							i.putExtras(extras);

							startActivityForResult(i, DETAILS_REQUEST_CODE);

						}
					});
			
			Intent intent = getIntent();
			String challengesJsonString = intent.getStringExtra(Consts.CHALLENGES_JSON_EXTRA);
			this.pendingChallenges = ChallengeUtil.jsonStringToChallengeList(challengesJsonString);
			this.mSize = pendingChallenges.size();
			
			
			adapter = new PendingChallengesListAdapter(this,
														R.id.listView_challenges, 
														this.pendingChallenges);
			
			this.listViewPending.setAdapter(adapter);

		} else {
			continueToMain();
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		if (id == R.id.action_logout) {
			if (HttpRequestSender.isNetworkAvailable(this)) {
				LoginActivity.mFbHelper.logout();
			}

			finish();
			return true;
		}

		if (id == R.id.action_details) {
			Intent i = new Intent(this, UserDetailsActivity.class);
			startActivity(i);
			
			return true;
		}
		
		return super.onOptionsItemSelected(item);
	}

	public void deleteAllPendingChallenges(View view) {
		
		if (deleteAll) {
			return;
		}
		deleteAll = true;
		
		for (int i = 0, size = pendingChallenges.size(); i < size; i++) {
			new DatabaseAsyncTask(this, DatabaseQueryOptions.COMPLETE)
					.execute(pendingChallenges.get(i).getID());
		}
		view.setVisibility(View.GONE);
		findViewById(R.id.button_uploadPendingChallenges).setVisibility(
				View.GONE);
		adapter.clear();
		adapter.notifyDataSetChanged();
	}

	public void uploadAllPendingChallenges(View view) {

		final Activity context = this;

		if (uploadAll) {
			return;
		}
		uploadAll = true;
		
		for (final ChallengeModel ch : pendingChallenges) {
			Bitmap bitmap = null;
			if (ch.getPhotoPath() != null) {
				bitmap = BitmapFactory.decodeFile(ch.getPhotoPath());
			}

			MessageType msgType = MessageType.CompleteChallenge;

			if (ch.getChallengedID() == ch.getChallenger().getFbID()) {
				msgType = MessageType.SelfChallenge;
			}

			MessageBuilder msgBuilder = new MessageBuilder(ch.getDescription(),
					ch.getAnswer(), ch.getHashtag(), msgType);

			LoginActivity.mFbHelper.postStatusUpdate(context,
					msgBuilder.build(), "" + ch.getChallenger().getFbID(),
					bitmap, new FacebookActionAdapter() {
						@Override
						public void onActionCompleted(Response response) {
							if (response.getError() == null) {
								new DatabaseAsyncTask(context,
										DatabaseQueryOptions.COMPLETE)
										.execute(ch.getID());
								adapter.remove(ch);
								Toast.makeText(context, "Challenge completed!",
										Toast.LENGTH_SHORT).show();
								
								if (adapter.isEmpty()) {
									if (dbFlag) {
										continueToMain();
									}
									fbFlag = true;
								}
							}
						}
					});

		}

		view.setVisibility(View.GONE);
		findViewById(R.id.button_deletePendingChallenges).setVisibility(
				View.GONE);
	}

	public void goToMain(View view) {
		if (adapter.isWorkInProgress() || (uploadAll && !adapter.isEmpty())) {
			Toast.makeText(this, "Please wait, working in progress", Toast.LENGTH_LONG).show();
			return;
		}
		continueToMain();
	}

	@Override
	public void processSeverResponse(ServerResponse response) {

	}

	@Override
	public void setHttpWorking(boolean working) {

	}

	@SuppressWarnings("unchecked")
	@Override
	public void processDatabaseResponse(DatabaseResponse result) {

		if (result.isSuccessful() &&
				result.getOption() == DatabaseQueryOptions.COMPLETE) {
			
			chCount++;
			Log.i("COUNT:", "" + chCount + " - " + mSize);
			
			if (!deleteAll) {
				adapter.decreaseActionsCount();
				if (mSize == chCount && !adapter.isWorkInProgress()) {
					continueToMain();
				}
			}
			
			if (deleteAll && mSize == chCount) {
				continueToMain();
			}
			
			if (fbFlag) {
				continueToMain();
			}
			dbFlag = true;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		
		if (HttpRequestSender.isNetworkAvailable(this)) {
			LoginActivity.mFbHelper.onActivityResult(this, requestCode,
					resultCode, data);
		}
		
		if (requestCode == DETAILS_REQUEST_CODE) {
			if (resultCode == RESULT_OK) {
				boolean success = data.getBooleanExtra(Consts.SUCCESS, false);
				if(success && (selectedChallenge != null)) {
					adapter.remove(selectedChallenge);
				}
			} else {
				selectedChallenge = null;
			}
			if (adapter.isEmpty() && !adapter.isWorkInProgress()) {
				continueToMain();
			}
		}
	}

	@Override
	public void setDatabaseWorking(boolean working) {
		this.databaseWorking = working;
	}

	private void continueToMain() {
		if (!toMain) {
			toMain = true;
			Intent intent = new Intent(this, MainActivity.class);
			startActivity(intent);
			finish();
		}
	}
}
